package com.ilop.sthome.ui.activity.config;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.text.TextUtils;

import com.example.common.base.BaseBindActivity;
import com.example.common.utils.SpUtil;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.utils.system.NetWorkUtil;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityNetWorkBinding;

/**
 * @author skygge
 * @date 2019-10-28.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：输入Wi-Fi密码页面
 */
public class NetWorkActivity extends BaseBindActivity<ActivityNetWorkBinding> {

	@Override
	protected int getLayoutId() {
		return R.layout.activity_net_work;
	}

	@Override
	protected void initListener() {
		super.initListener();
		mDBind.ivConfigBack.setOnClickListener(v -> finish());
		mDBind.ivWifiChange.setOnClickListener(v -> {
			Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
			startActivity(intent);
		});
		mDBind.btnConfirm.setOnClickListener(v -> {
			hideSoftKeyboard();
			String apSsId = mDBind.tvWifiSsId.getText().toString();
			String apPassword = mDBind.etWifiPwd.getCodeEdit().getText().toString();

			if(TextUtils.isEmpty(apSsId) || apSsId.equals(getString(R.string.no_wifi))){
				showToast(getString(R.string.no_wifi));
			}else if(TextUtils.isEmpty(apPassword)){
				showToast(getString(R.string.password_is_empty));
			}else{
				Intent intent = new Intent(mContext, ConnectNetActivity.class);
				intent.putExtra(CommonId.KEY_WIFI_SSID, apSsId);
				intent.putExtra(CommonId.KEY_WIFI_PWD, apPassword);
				startActivity(intent);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		String wifi_ssId = NetWorkUtil.getInstance().getWifiConnectedSSId(mContext);
		if (wifi_ssId != null) {
			if(wifi_ssId.contains("ssid")){ //兼容某些8.0以上手机
				ConnectivityManager mManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				if (mManager!=null){
					NetworkInfo networkInfo = mManager.getActiveNetworkInfo();
					if (networkInfo != null) {
						wifi_ssId = networkInfo.getExtraInfo().replace("\"", "");
					}
				}
			}
			mDBind.tvWifiSsId.setText(wifi_ssId);
		} else {
			mDBind.tvWifiSsId.setText(getString(R.string.no_wifi));
		}
		String wifi_pwd = SpUtil.getString(mContext, wifi_ssId, "");
		mDBind.etWifiPwd.getCodeEdit().setText(wifi_pwd);
		mDBind.etWifiPwd.setCodeShow(false);
	}
}
